package com.cd.common.util;

import com.cd.common.domain.LoginUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Random;

/**
 * @Description security相关的工具类
 * @Author lqq
 * @Date 2023/11/17 13:33
 **/
public class AuthUtils {

    // 字母池（大写字母）
    private static final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // 数字池
    private static final String NUMBERS = "0123456789";
    // 随机数生成器
    private static final Random random = new Random();


    /**
     * Get the current username.
     *
     * @return the username of the currently logged-in user, or null if not logged in
     */
    public static String currentUsername() {
        return SecurityContextHolder.getContext().getAuthentication() == null ? null
                : SecurityContextHolder.getContext().getAuthentication().getName();
    }

    /**
     * Get the information of the logged-in user.
     *
     * @return The information of the logged-in user.
     */
    public static LoginUser getLoginUser() {
        return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /**
     * @Description get current userId
     * @Author lqq
     * @Date 2024/1/25 14:29
     **/
    public static Long currentUserId() {
        return ((LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
                .getUser().getUserId();
    }



    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * @Description 随机生成用户名
     * @Author lqq
     * @Date 2025/3/27 17:38
     **/
    // 生成六位随机字母
    private static String generateRandomLetters() {
        StringBuilder letters = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(LETTERS.length());
            letters.append(LETTERS.charAt(index));
        }
        return letters.toString();
    }

    // 生成六位随机数字
    private static String generateRandomNumbers() {
        StringBuilder numbers = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(NUMBERS.length());
            numbers.append(NUMBERS.charAt(index));
        }
        return numbers.toString();
    }

    // 生成六位字母 + 六位数字的随机字符串
    public static String generateRandomString() {
        return generateRandomLetters() + generateRandomNumbers();
    }


}
